<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>标签管理测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
        }
        .test-section h3 {
            margin-top: 0;
            color: #333;
        }
        button {
            background-color: #409eff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #367fd1;
        }
        input, textarea, select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 5px;
        }
        .label-item {
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #eee;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .color-swatch {
            width: 20px;
            height: 20px;
            border-radius: 3px;
            border: 1px solid #ccc;
        }
        #output {
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <h1>标签管理功能测试</h1>
    
    <div class="test-section">
        <h3>1. 获取所有标签</h3>
        <button onclick="loadLabels()">加载标签列表</button>
        <div id="labelsList"></div>
    </div>
    
    <div class="test-section">
        <h3>2. 创建新标签</h3>
        <input type="text" id="newLabelName" placeholder="标签名称" />
        <input type="color" id="newLabelColor" value="#409eff" />
        <select id="newLabelParent">
            <option value="">无父级</option>
        </select>
        <input type="text" id="newLabelDesc" placeholder="描述（可选）" />
        <input type="number" id="newLabelSort" value="0" placeholder="排序" />
        <button onclick="createLabel()">创建标签</button>
    </div>
    
    <div class="test-section">
        <h3>3. 更新标签</h3>
        <select id="updateLabelId">
            <option value="">选择要更新的标签</option>
        </select>
        <input type="text" id="updateLabelName" placeholder="新标签名称" />
        <input type="color" id="updateLabelColor" value="#409eff" />
        <button onclick="updateLabel()">更新标签</button>
    </div>
    
    <div class="test-section">
        <h3>4. 删除标签</h3>
        <select id="deleteLabelId">
            <option value="">选择要删除的标签</option>
        </select>
        <button onclick="deleteLabel()" style="background-color: #f56c6c;">删除标签</button>
    </div>
    
    <div class="test-section">
        <h3>输出</h3>
        <div id="output"></div>
    </div>

    <script>
        const API_BASE = '/api';  // 根据实际情况调整
        let labels = [];

        function log(message) {
            const output = document.getElementById('output');
            const timestamp = new Date().toLocaleTimeString();
            output.textContent += `[${timestamp}] ${message}\n`;
            output.scrollTop = output.scrollHeight;
        }

        async function apiCall(method, url, data = null) {
            try {
                const options = {
                    method,
                    headers: {
                        'Content-Type': 'application/json',
                    }
                };
                
                if (data) {
                    options.body = JSON.stringify(data);
                }
                
                const response = await fetch(API_BASE + url, options);
                const result = await response.json();
                
                if (response.ok) {
                    log(`✅ ${method} ${url} - 成功`);
                    return result;
                } else {
                    log(`❌ ${method} ${url} - 失败: ${result.message || response.statusText}`);
                    return null;
                }
            } catch (error) {
                log(`❌ ${method} ${url} - 错误: ${error.message}`);
                return null;
            }
        }

        async function loadLabels() {
            const result = await apiCall('GET', '/labels');
            if (result?.data) {
                labels = result.data;
                renderLabels();
                updateSelects();
                log(`加载了 ${labels.length} 个标签`);
            }
        }

        function renderLabels() {
            const container = document.getElementById('labelsList');
            container.innerHTML = '';
            
            if (labels.length === 0) {
                container.innerHTML = '<p>暂无标签</p>';
                return;
            }
            
            labels.forEach(label => {
                const div = document.createElement('div');
                div.className = 'label-item';
                div.innerHTML = `
                    <div class="color-swatch" style="background-color: ${label.color || '#ddd'}"></div>
                    <span><strong>${label.name}</strong></span>
                    <span>${label.description || ''}</span>
                    <span>排序: ${label.sort}</span>
                    <span>ID: ${label.id}</span>
                `;
                container.appendChild(div);
            });
        }

        function updateSelects() {
            const parentSelect = document.getElementById('newLabelParent');
            const updateSelect = document.getElementById('updateLabelId');
            const deleteSelect = document.getElementById('deleteLabelId');
            
            // 清空现有选项（保留第一个）
            parentSelect.innerHTML = '<option value="">无父级</option>';
            updateSelect.innerHTML = '<option value="">选择要更新的标签</option>';
            deleteSelect.innerHTML = '<option value="">选择要删除的标签</option>';
            
            labels.forEach(label => {
                const parentOption = document.createElement('option');
                parentOption.value = label.id;
                parentOption.textContent = label.name;
                parentSelect.appendChild(parentOption);
                
                const updateOption = document.createElement('option');
                updateOption.value = label.id;
                updateOption.textContent = label.name;
                updateSelect.appendChild(updateOption);
                
                const deleteOption = document.createElement('option');
                deleteOption.value = label.id;
                deleteOption.textContent = label.name;
                deleteSelect.appendChild(deleteOption);
            });
        }

        async function createLabel() {
            const name = document.getElementById('newLabelName').value.trim();
            const color = document.getElementById('newLabelColor').value;
            const parentId = document.getElementById('newLabelParent').value || null;
            const description = document.getElementById('newLabelDesc').value.trim() || null;
            const sort = parseInt(document.getElementById('newLabelSort').value) || 0;
            
            if (!name) {
                log('❌ 请输入标签名称');
                return;
            }
            
            const data = {
                name,
                color,
                parent_id: parentId,
                description,
                sort
            };
            
            const result = await apiCall('POST', '/labels', data);
            if (result) {
                log(`✅ 创建标签成功: ${name}`);
                // 清空表单
                document.getElementById('newLabelName').value = '';
                document.getElementById('newLabelDesc').value = '';
                // 重新加载标签列表
                await loadLabels();
            }
        }

        async function updateLabel() {
            const labelId = document.getElementById('updateLabelId').value;
            const name = document.getElementById('updateLabelName').value.trim();
            const color = document.getElementById('updateLabelColor').value;
            
            if (!labelId) {
                log('❌ 请选择要更新的标签');
                return;
            }
            
            if (!name) {
                log('❌ 请输入新的标签名称');
                return;
            }
            
            const currentLabel = labels.find(l => l.id === labelId);
            const data = {
                name,
                color,
                parent_id: currentLabel?.parent_id || null,
                description: currentLabel?.description || null,
                sort: currentLabel?.sort || 0
            };
            
            const result = await apiCall('PUT', `/labels/${labelId}`, data);
            if (result) {
                log(`✅ 更新标签成功: ${name}`);
                // 清空表单
                document.getElementById('updateLabelName').value = '';
                // 重新加载标签列表
                await loadLabels();
            }
        }

        async function deleteLabel() {
            const labelId = document.getElementById('deleteLabelId').value;
            
            if (!labelId) {
                log('❌ 请选择要删除的标签');
                return;
            }
            
            const label = labels.find(l => l.id === labelId);
            if (!confirm(`确定要删除标签"${label?.name}"吗？`)) {
                return;
            }
            
            const result = await apiCall('DELETE', `/labels/${labelId}`);
            if (result) {
                log(`✅ 删除标签成功: ${label?.name}`);
                // 重新加载标签列表
                await loadLabels();
            }
        }

        // 页面加载时自动加载标签
        document.addEventListener('DOMContentLoaded', loadLabels);
    </script>
</body>
</html>
